//
//  ViewController.m
//  24-EncryptionHomework
//
//  Created by 曹曹 on 16/8/16.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"
#import "NSString+GX_MD5.h"

#define kEncryptURLString @"http://tool.zzblo.com/api/md5/encrypt"
#define kDecryptURLString @"http://tool.zzblo.com/api/md5/decrypt"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *originTextField;
@property (weak, nonatomic) IBOutlet UITextField *encryptedTextField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}
// 解密
- (IBAction)decryptAction:(id)sender {
    [self postRequestWithURLString:kDecryptURLString Option:@"secret" parameter:_encryptedTextField.text];
}
// 加密
- (IBAction)encryptAction:(id)sender {
    [self postRequestWithURLString:kEncryptURLString Option:@"text" parameter:_originTextField.text];
}
- (void)postRequestWithURLString:(NSString *)urlString Option:(NSString *)option parameter:(NSString *)param {
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    [session.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    NSString *parameter = [NSString stringWithFormat:@"%@=%@", option, param];
    [session POST:urlString parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([option isEqualToString:@"text"]) {
            _encryptedTextField.text = [responseObject objectForKey:@"secret32"];
            NSLog(@"加密成功:%@", responseObject);
        } else if ([option isEqualToString:@"secret"]) {
            _originTextField.text = [responseObject objectForKey:@"text"];
            NSLog(@"解密成功:%@", responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

// MD5
- (IBAction)MD5Action:(id)sender {
    _encryptedTextField.text = [_encryptedTextField.text MD5String32BitsLowercase];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
